use dirs;
use std::fs;

pub fn init_config() -> Result<(), Box<dyn std::error::Error>> {
    let config_dir = dirs::home_dir()
        .ok_or("Cannot find home directory")?
        .join(".config/yk");

    let config_file = config_dir.join("config.json");
    let source_dir = config_dir.join("source");

    // Create configuration directory
    fs::create_dir_all(&config_dir)?;
    fs::create_dir_all(&source_dir)?;

    // Create default configuration file
    let default_config = r#"{
  "languages": {
    "python": {
      "extension": "py",
      "interpreter": "python"
    },
    "javascript": {
      "extension": "js", 
      "interpreter": "node"
    },
    "ruby": {
      "extension": "rb",
      "interpreter": "ruby"
    },
    "scheme": {
      "extension": "scm",
      "interpreter": "scheme"
    },
    "zsh": {
      "extension": "sh",
      "interpreter": "zsh"
    },
    "bash": {
      "extension": "sh",
      "interpreter": "bash"
    },
    "shell": {
      "extension": "sh",
      "interpreter": "sh"
    },
    "sh": {
      "extension": "sh",
      "interpreter": "sh"
    },
    "typst": {
      "extension": "typ",
      "interpreter": "typst"
    },
    "typescript": {
      "extension": "ts",
      "interpreter": "ts-node"
    },
    "bun": {
      "extension": "js",
      "interpreter": "bun"
    },
    "lua": {
      "extension": "lua",
      "interpreter": "lua"
    },
    "pypy": {
      "extension": "py",
      "interpreter": "pypy"
    },
    "fish": {
      "extension": "fish",
      "interpreter": "fish"
    },
    "nu": {
      "extension": "nu",
      "interpreter": "nu"
    },
    "julia": {
      "extension": "jl",
      "interpreter": "julia"
    },
    "powershell": {
      "extension": "ps1",
      "interpreter": "pwsh"
    },
    "pwsh": {
      "extension": "ps1",
      "interpreter": "pwsh"
    },
    "cmd": {
      "extension": "cmd",
      "interpreter": "cmd"
    },
    "perl": {
      "extension": "pl",
      "interpreter": "perl"
    },
    "php": {
      "extension": "php",
      "interpreter": "php"
    },
    "r": {
      "extension": "r",
      "interpreter": "R"
    },
    "Rscript": {
      "extension": "R",
      "interpreter": "Rscript"
    },
    "tcl": {
      "extension": "tcl",
      "interpreter": "tclsh"
    },
    "groovy": {
      "extension": "groovy",
      "interpreter": "groovy"
    }
  }
}"#;

    if !config_file.exists() {
        fs::write(&config_file, default_config)?;
        // Configuration file created
    } else {
        // Configuration file already exists
    }

    // Create example markdown file
    let example_file = source_dir.join("example.md");
    if !example_file.exists() {
        let example_content = r#"# Code Snippet Example

## Python Example1
```python
# Print Hello World
print("Hello, World!")
```

## Python Example2
```python
# Add two numbers
"""
A command-line program that accepts two numbers and returns their sum.
"""

import sys
import argparse


def add_numbers(num1, num2):
    """Add two numbers and return the result."""
    return num1 + num2


def main():
    """Main function to handle command-line arguments and execute the program."""
    parser = argparse.ArgumentParser(
        description="Add two numbers together",
        usage="%(prog)s num1 num2"
    )
    parser.add_argument("num1", type=float, help="First number")
    parser.add_argument("num2", type=float, help="Second number")
    
    # If no arguments provided, show help
    if len(sys.argv) == 1:
        parser.print_help()
        return 1
    
    try:
        args = parser.parse_args()
        result = add_numbers(args.num1, args.num2)
        print(f"{args.num1} + {args.num2} = {result}")
        return 0
    except ValueError as e:
        print(f"Error: Invalid input. Please provide valid numbers.", file=sys.stderr)
        return 1
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
```

## JavaScript Example
```javascript
// Print current time
console.log(new Date().toISOString());
```

## Bash Example
```bash
# List files in current directory
ls -la
```
"#;
        fs::write(&example_file, example_content)?;
        // Example file created
    } else {
        // Example file already exists
    }

    println!("Initialization completed");

    Ok(())
}
